import { useStorePermission, useStoreUser } from '@/store';
const allowList = ['login', 'register']; // no redirect allowList

export default function createPermissionGuard(router) {
  const storePermission = useStorePermission();
  const storeUser = useStoreUser();
  router.beforeEach(async (to, from, next) => {
    console.log('to',to);
    storePermission.changeValue('curRoute', to);
    if (storeUser.token) {
      if (to.path != '/login') {
        if (!storePermission.addRouters.length) {
          try {
            // eslint-disable-next-line new-cap
            const addRouter = await storePermission.GenerateRoutes();
            addRouter.forEach(r => {
              router.addRoute(r);
            });

            if (to.path == '/') {
              const getPath = item => {
                if (item.children && item.children.length > 0) {
                  return getPath(item.children[0]);
                } else {
                  return item.path;
                }
              };
              const path = getPath(addRouter[0]);
              // 动态路由第一个页面
              next({
                path,
              });
            }
            // 请求带有 redirect 重定向时，登录自动重定向到该地址
            // 动态添加路由后，此处应当重定向到fullPath，否则会加载404页面内容
            const redirect = decodeURIComponent(from.query.redirect || to.fullPath);
            next({
              path: redirect,
              replace: true,
              query: to.query,
            });
          } catch (error) {
            console.log(error);
            next({
              path: '/login',
            });
          }
          return;
        }
        if (!storeUser.userInfo) {
          try {
            // await storeUser.getUserInfo();
            // eslint-disable-next-line no-unused-vars
          } catch (err) {
            next();
            return;
          }
        }
         if(to.name == "feedback-list"){
          await  storeUser.getFeedBackNum()
          }
        if (to.matched.length !== 0) {
          next();
          // 如果匹配到跳转下一页
        } else {
          // 没有匹配到的话，跳转404
          next({
            path: '/404',
          });
        }
        return;
      } else {
        next({
          path: '/',
        });
      }
    } else {
      // 在免登录名单，直接进入
      if (allowList.includes(to.name)) {
        next();
      } else {
        next({
          path: '/login',
          query: {
            redirect: to.fullPath,
          },
        });
      }
    }
  });
}
